<%@page import="fr.insta.reverse.uml.routing.Route"%>
<%@page contentType="text/html; charset=UTF-8"%>
<%@page pageEncoding="UTF-8"%>

<noscript id="diagramScript"><%= request.getAttribute("diagram").toString() %></noscript>
<script>

	$('document').ready(function(){
		yumlImageRequest();
	});
	
	function yumlImageRequest(){
		
		//Get the uml code inside the div
		scriptYuml = $('#diagramScript').html();
		
		//scriptYuml = cleanDsl(scriptYuml);
		scriptYuml = cleanDsl(scriptYuml);
		
		$.ajax({
			type: 'POST',
			timeout: 30000,
			url: '<%= Route.WSGetImageUml.getAbsoluteRoute(request)%>',
			data: {
				scriptUml : scriptYuml,
				hash : "<%= request.getAttribute("hash") %>"
			},
			success: function(data, textStatus, jqXHR){
				renderImageFromName(data);
			},
			error: function(jqXHR, textStatus, errorThrown) {
				failedImage();
			}
		});
	}
	
	function renderImageFromName(data){
		
		var elem = data.split(";");
		
		imgName = elem[0];
		
		var img = $("<img style='max-width:100%'/>")
	    .attr('src', "http://yuml.me/" + imgName)
	    .load(function(){
	    	
	    	imageFailedToLoad = !this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0;
	
	    	if (imageFailedToLoad) {
	    		failedImage();	
	    	} else {
	    		successImage(img);
	    		
	    		if(elem.length == 2){
	    			
	    			var idProjectCreated = elem[1];
	    			
	    			$("#project_link").html('<a href="<%=Route.ProjectView.getAbsoluteRoute(request) %>?id='+idProjectCreated+'">Naviguer vers le projet</a>');
	    		}
	    	}
	    });
	}
	
	function successImage(img){
		$("#diagram").append(img);
		$("#diagram").removeClass("loading");
		$("#info").html("Votre diagramme a bien été généré.");
	}
	
	function failedImage(){
		$("#diagram").removeClass("loading");
		$("#info").html("La génération du diagramme a échoué.");
	}
	
	function cleanDsl(dsl)
	{
		tmp = dsl;
		tmp = dsl.replace(/(\n|\r|\t)+$/, '');
		tmp = tmp.replace(/\n/g,', ').replace(/,,/g,',').replace(/, $/,'');
		return tmp;
	}

</script>

<h4 id="info">Votre diagramme UML est en train d'être généré.</h4>

<div id="diagram" class="loading"></div>

<div id="project_link">
</div>